package com.ayf.payment.game.api.service.platform.impl;

import cn.hutool.core.collection.CollUtil;
import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.dto.platform.NetConfigDTO;
import com.ayf.payment.game.api.entity.platform.WxAutoReplyConfig;
import com.ayf.payment.game.api.entity.platform.WxConfig;
import com.ayf.payment.game.api.entity.platform.WxUser;
import com.ayf.payment.game.api.mapper.platform.WxUserMapper;
import com.ayf.payment.game.api.service.platform.*;
import com.ayf.payment.game.api.utils.JsonUtils;
import com.ayf.payment.game.api.wx.MyConstant;
import com.ayf.payment.game.api.wx.WxHttpUtil;
import com.ayf.payment.game.api.wx.WxSendMsgUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.jdom2.Element;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class WxPushMessageServiceImpl implements WxPushMessageService {

    @Autowired
    private WxConfigService wxConfigService;
    @Resource
    private WxUserMapper wxUserMapper;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private WxAutoReplyConfigService wxAutoReplyConfigService;
    @Autowired
    private RedisCacheUtil redisCacheUtil;
    @Autowired
    private WxSendMsgUtils wxSendMsgUtils;
    @Autowired
    private NetConfigService netConfigService;
    @Autowired
    private MyConstant myConstant;

    /**
     * 获取xml
     *
     * @param root 根节点
     * @return String 类型的xml
     */
    @Override
    public String messageHandle(Element root) {
        String xml = "";
        //开发者微信号
        String toUserName = root.getChildText("ToUserName");
        //发送方帐号（一个OpenID）
        String fromUserName = root.getChildText("FromUserName");
        //消息创建时间 （整型）
        String createTime = root.getChildText("CreateTime");
        //消息类型
        String msgType = root.getChildText("MsgType");
        //事件
        String event = root.getChildText("Event");
        //内容
        String content = root.getChildText("Content");
        LogPortal.info("微信消息管理参数[toUserName:{},fromUserName:{},createTime:{},msgType:{},event:{},content:{}]",
                toUserName, fromUserName, createTime, msgType, event, content);
        WxUser dbWxUser = wxUserMapper.selectWxUserByOpenid(fromUserName);
        if ("event".equals(msgType)) {
            //进入事件类型消息
            String eventKey = root.getChildText("EventKey");
            LogPortal.info("[{}]进入事件类型消息,场景值[{}]", fromUserName, eventKey);
            xml = getEventXml(dbWxUser, event, eventKey, fromUserName, toUserName);
        } else if ("text".equals(msgType)) {
            //进入文本类型消息
            LogPortal.info("[{}]进入文本类型消息", fromUserName);
            xml = getTextXml(fromUserName, toUserName, content);
        } else if ("image".equals(msgType)) {
            //进入图片类型消息
            LogPortal.info("[{}]进入图片类型消息", fromUserName);
        } else if ("voice".equals(msgType)) {
            //进入语音类型消息
            LogPortal.info("[{}]进入语音类型消息", fromUserName);
        } else if ("video".equals(msgType)) {
            //进入视频类型消息
            LogPortal.info("[{}]进入视频类型消息", fromUserName);
        } else if ("shortvideo".equals(msgType)) {
            //进入小视频类型消息
            LogPortal.info("[{}]进入小视频类型消息", fromUserName);
        } else if ("location".equals(msgType)) {
            //进入地址类型消息
            LogPortal.info("[{}]进入地址类型消息", fromUserName);
        } else if ("link".equals(msgType)) {
            //进入链接类型消息
            LogPortal.info("[{}]进入链接类型消息", fromUserName);
        }
        return xml;
    }

    /**
     * 获取文本消息回复
     *
     * @param fromUserName 接收方
     * @param toUserName   发送方
     * @return string类型的xml
     */
    private String getTextXml(String fromUserName, String toUserName, String content) {
//        String accountName = redisCacheUtil.getObjectFromCache(getUnbindKey(content, fromUserName));
//        if (StringUtils.isNotBlank(accountName)) {
//            boolean boo = wxUserService.unBindWx(fromUserName);
//            if (boo) {
//                redisCacheUtil.delete(getUnbindKey(content, fromUserName));
//                wxSendMsgUtils.unbindWx(fromUserName, accountName);
//            }
//        }
        List<WxAutoReplyConfig> list = wxAutoReplyConfigService.getListByConfigId(1);
        if (CollUtil.isNotEmpty(list)) {
            for (WxAutoReplyConfig wxAutoReplyConfig : list) {
                if (content.equals(wxAutoReplyConfig.getKey())) {
                    return formatTextXml(fromUserName, toUserName, wxAutoReplyConfig.getValue());
                }
            }
        }
        return "";
    }

    public String formatTextXml(String fromUserName, String toUserName, String content) {
        return "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + content + "]]></Content>\n" +
                "</xml>";
    }

    /**
     * @param event        事件
     * @param fromUserName 接收者
     * @param toUserName   发送者
     * @return String类型的xml
     */
    private String getEventXml(WxUser dbWxUser, String event, String eventKey, String fromUserName, String toUserName) {
        WxConfig config = wxConfigService.getConfig();
        if (config.getStatus() == 0) {
            return "";
        }
        String xml = "";
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + myConstant.getAccessToken(config) + "&openid=" + fromUserName + "&lang=zh_CN";
        JSONObject jsonObject = WxHttpUtil.doGet("getWxUserInfo_".concat(fromUserName),url);
        WxUser wxUser = JsonUtils.fromJson(jsonObject.toString(), WxUser.class);
        if ("subscribe".equals(event)) {
            LogPortal.info("[{}]进入关注类型消息", fromUserName);
            LogPortal.info("场景值[{}]", eventKey);
//            if (eventKey.contains("qrToken-")) {
//                QrToken qrToken = new QrToken();
//                qrToken.setStatus(0);
//                qrToken.setOpenid(fromUserName);
//                redisCacheUtil.setObjectToCache("QR-CODE-LOGIN-TOKEN:" + eventKey, qrToken, 300L, TimeUnit.SECONDS);
//            } else
            if (eventKey.contains("BIND")) {
                String[] arr = eventKey.split("_");
                //判断是否拥有场景值
                if (arr.length > 1) {
                    bindWx1(wxUser, arr[1], fromUserName);
                }
            }
            if (dbWxUser == null) {
                wxUser.setSubscribetime(new Date());
                if (wxUserMapper.insertSelective(wxUser) > 0) {
                    LogPortal.info("用户[{}]关注成功", wxUser.getOpenid());
                }
            } else {
                wxUser.setId(dbWxUser.getId());
                if (wxUserMapper.updateByPrimaryKeySelective(wxUser) > 0) {
                    LogPortal.info("用户[{}]关注成功", dbWxUser.getOpenid());
                }
            }
            xml = formatTextXml(fromUserName, toUserName, config.getAttentionReply());
        } else if ("unsubscribe".equals(event)) {
            LogPortal.info("[{}]进入取消关注类型消息", fromUserName);
            if (wxUserService.changeWxUserSubscribe(dbWxUser)) {
                LogPortal.info("用户[{}]取消关注成功", dbWxUser.getOpenid());
            }
        } else if ("SCAN".equals(event)) {
            LogPortal.info("[{}]进入扫码二维码类型消息", fromUserName);
            LogPortal.info("场景值[{}]", eventKey);

            if (eventKey.contains("BIND")) {
                bindWx2(wxUser, dbWxUser, eventKey, fromUserName, 2);
            }
//            else if (eventKey.contains("qrToken-")) {
//                QrToken qrToken = new QrToken();
//                if (dbWxUser == null || dbWxUser.getType() == null || dbWxUser.getMerchantId() == null || dbWxUser.getLoginId()
//                        == null) {
//                    qrToken.setStatus(0);
//                    qrToken.setOpenid(fromUserName);
//                    xml = formatTextXml(fromUserName, toUserName, "请先将账号与公众号绑定");
//                } else {
//                    if (dbWxUser.getType() == 1) {
//                        qrToken.setLoginId(dbWxUser.getMerchantId());
//                        qrToken.setLoginType(LoginType.FATHER.name());
//                    } else if (dbWxUser.getType() == 2) {
//                        qrToken.setLoginId(dbWxUser.getLoginId());
//                        qrToken.setLoginType(LoginType.SON.name());
//                    } else {
//                        qrToken.setLoginId(dbWxUser.getLoginId());
//                        qrToken.setLoginType("TuiG");
//                    }
//                    qrToken.setStatus(1);
//                    qrToken.setWxName(dbWxUser.getNickname());
//                    qrToken.setMerchantId(dbWxUser.getMerchantId());
//                }
//                redisCacheUtil.setObjectToCache("QR-CODE-LOGIN-TOKEN:" + eventKey, qrToken, 300L, TimeUnit.SECONDS);
//            }
        } else if ("CLICK".equals(event)) {
            LogPortal.info("[{}]进入点击菜单事件", fromUserName);
            if ("KE_FU".equals(eventKey)) {
                LogPortal.info("[{}]进入获取客服信息事件", fromUserName);
                NetConfigDTO netConfig = netConfigService.getNetConfig();
                if (StringUtils.isEmpty(netConfig.getPlatContactInfo())) {
                    xml = formatTextXml(fromUserName, toUserName, "暂无客服");
                } else {
                    xml = formatTextXml(fromUserName, toUserName, netConfig.getPlatContactInfo());
                }
            }
        }
        return xml;
    }

    private String getUnbindKey(String accountName, String openid) {
        return "UN_BIND_KEY:" + accountName + "_" + openid;
    }

    private void bindWx1(WxUser wxUser, String eventKey, String fromUserName) {
        String[] str = eventKey.split(";");
        if (str.length >= 5) {
            wxUser.setOpenid(fromUserName);
            if (formatBind(wxUser, str)) {
                wxSendMsgUtils.bindWx(fromUserName, str[1], wxUser.getBindTime(), "微信扫码绑定");
                LogPortal.info("账号[{}]与微信[{}]绑定成功", wxUser.getOpenid(), fromUserName);
            }
        }
    }

    private void bindWx2(WxUser wxUser, WxUser dbWxUser, String eventKey, String fromUserName, int a) {
        String[] str = eventKey.split(";");
        if (str.length >= 5) {
            wxUser.setOpenid(fromUserName);
            if (formatBind(wxUser, str)) {
                if (dbWxUser == null) {
                    wxUserMapper.insertSelective(wxUser);
                    wxSendMsgUtils.bindWx(fromUserName, str[1], wxUser.getBindTime(), "微信扫码绑定");
                    LogPortal.info("账号[{}]与微信[{}]绑定成功", wxUser.getLoginId(), fromUserName);
                } else if (dbWxUser.getLoginId() != null) {
                    if (!(dbWxUser.getLoginId().equals(wxUser.getLoginId()) && dbWxUser.getMerchantId().equals(wxUser.getMerchantId()))) {
                        String why = "该微信已绑定其它账号，请先进行解绑";
                        wxSendMsgUtils.bindWxFail(fromUserName, why, "微信扫码绑定");
                    }
                } else {
                    wxUser.setId(dbWxUser.getId());
                    wxUserMapper.updateByPrimaryKeySelective(wxUser);
                    wxSendMsgUtils.bindWx(fromUserName, str[1], wxUser.getBindTime(), "微信扫码绑定");
                    LogPortal.info("账号[{}]与微信[{}]绑定成功", wxUser.getLoginId(), fromUserName);
                }
            }
        }
    }

    private boolean formatBind(WxUser wxUser, String[] str) {
        Integer merchantId = Integer.valueOf(str[2]);
        Integer loginId = Integer.valueOf(str[3]);
        int type = Integer.parseInt(str[4]);

        List<WxUser> list = wxUserService.getWxUser(loginId, merchantId);
        if (CollUtil.isNotEmpty(list)) {
            WxUser wxUser1 = list.get(0);
            if (!wxUser1.getOpenid().equals(wxUser.getOpenid())) {
                String why = "绑定失败，该账号已绑定微信【" + wxUser1.getNickname() + "】，请先进行解绑";
                wxSendMsgUtils.bindWxFail(wxUser.getOpenid(), why, "如果微信【" + list.get(0).getNickname() + "】已不使用，请联系运营人员解绑");
                return false;
            }
        }

        wxUser.setMerchantId(merchantId);
        wxUser.setLoginId(loginId);
        wxUser.setType(type);
        if (type == 1) {
            wxUser.setWxMsgStatus(1);
            wxUser.setLoginRemindStatus(1);
        } else {
            wxUser.setWxMsgStatus(0);
            wxUser.setLoginRemindStatus(0);
        }
        Date date = new Date();
        wxUser.setBindTime(date);
        return true;
    }
}
